<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/27
// +----------------------------------------------------------------------

namespace app\index\controller\api;

use app\common\constants\ApiConstant;
use app\common\facade\Arr;
use app\common\facade\TransItem;
use app\common\services\UserWalletService;
use think\App;
use think\Db;

/**
 *
 * Class UserWallet
 * @package app\index\controller\api
 * @author feraner<feraner@163.com>
 * @date 2019/11/27
 */
class UserWallet extends ApiBase
{

    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }


    /**
     * 钱包中心首页
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        
        $walletInfo = Db::name('user_wallet')
            ->where('user_id', $this->userId)
            ->find() ?: [];

        $publishBeanRate = sysconf('publish_job_bean_rate');
        
        
        $this->response([
            'walletInfo'        => $walletInfo,
            'publishBeanRate'   => $publishBeanRate
        ]);
    }


    /**
     * 发布豆记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function beanList()
    {
        $type = $this->request->param('type', 0);
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', 10);

        $beanListDb = Db::name('user_recharge_log')->alias('url')
            ->where('url.publish_bean', '>', 0)
            ->where('url.user_id', $this->userId);
        if ($type) {
            $beanListDb->where('url.type', $type);
        }
        $beanList = $beanListDb->join('user_charge uc', 'url.charge_id = uc.id', 'LEFT')
            ->order('url.id DESC')
            ->page($page, $pageSize)
            ->field('url.*,uc.order_no as payOrderNo,uc.status as payStatus,uc.money as payMoney')
            ->select() ?: [];

        foreach ($beanList as &$item) {
            $item['buyTime'] = date('Y-m-d H:i', Arr::get($item, 'created_at'));
            $item['statusCh'] = '已完成';
            if (Arr::get($item, 'charge_id')) {
                //充值记录
                $item['statusCh'] = TransItem::transBeanPayStatus(Arr::get($item, 'payStatus'));
            }
            if (Arr::valueEq($item, 'type', 2)) {
                $item['statusCh'] = '已扣除';
            }
            $item['kindCh'] = TransItem::transBeanOption(Arr::get($item, 'kind'));
        }
        $this->response($beanList);
    }


    /**
     * 积分消耗列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function creditsList()
    {
        $type = $this->request->param('type', 0);
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', 10);

        $creditsListDb = Db::name('user_credits_log')
            ->where('credits', '>', 0)
            ->where('user_id', $this->userId);

        if ($type) {
            $creditsListDb->where('type', $type);
        }
        $creditsList = $creditsListDb->order('id DESC')
            ->page($page, $pageSize)
            ->select() ?: [];

        foreach ($creditsList as &$item) {
            $item['kindCh'] = TransItem::transCreditsOption(Arr::get($item, 'kind'));
            $item['timeCh'] = date('Y-m-d H:i', Arr::get($item, 'created_at'));
        }

        $this->response($creditsList);
    }


    /**
     * 用户取消充值订单
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function cancelRechargeBean()
    {
        //todo::这里需要重新处理
        $rechargeId = $this->request->post('id', 0);
        if ($rechargeId) {
            Db::name('user_charge')
                ->where('id', $rechargeId)
                ->update([
                    'status'        => 2,
                    'updated_at'    => time()
                ]);
            $this->response([
                'status'        => 2,
                'statusCh'      => TransItem::transBeanPayStatus(2),
                'chargeId'      => $rechargeId
            ]);
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }





    /**
     * 用户充值兑换发布豆
     */
    public function rechargeBean()
    {
        $postData = $this->request->post();
        if (Arr::get($postData, 'totalMoney') && Arr::get($postData, 'totalExchangeBean')) {
            $postData['user_id'] = $this->userId;
            try {
                $result = (new UserWalletService())->rechargeBean($postData);
                if ($result) {
                    $this->response([
                        'chargeId'      => $result
                    ]);
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
            $this->response(
                [],
                ApiConstant::API_ERROR,
                ApiConstant::API_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }


    /**
     * 用户活动充值发布豆
     */
    public function activeRechargeBean()
    {
        $postData = $this->request->post();
        if (Arr::get($postData, 'totalMoney', 0) &&
            Arr::get($postData, 'totalExchangeBean', 0) &&
            Arr::get($postData, 'activeId', 0)) {
            $postData['user_id'] = $this->userId;
            try {
                $result = (new UserWalletService())->activeRechargeBean($postData);
                if ($result) {
                    $this->response([
                        'chargeId'      => $result
                    ]);
                }
            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
            $this->response(
                [],
                ApiConstant::API_ERROR,
                ApiConstant::API_ERROR_STR
            );
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );
    }








    /**
     * 微信支付订单信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wechatPayInfo()
    {
        $chargeId = $this->request->post('chargeId', 0);
        if ($chargeId) {

            try {
                $result = (new UserWalletService())->getWechatInfo($chargeId);
                if ($result) {
                    $this->response($result);
                }

            } catch (\Exception $e) {
                $this->response(
                    [],
                    ApiConstant::API_ERROR,
                    $e->getMessage()
                );
            }
        }
        $this->response(
            [],
            ApiConstant::API_PARAMETER_ERROR,
            ApiConstant::API_PARAMETER_ERROR_STR
        );

    }


    /**
     * 信用分操作记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function scoreList()
    {
        $page = $this->request->param('page', 1);
        $pageSize = $this->request->param('pageSize', 10);

        $creditsListDb = Db::name('user_score_log')
            ->where('credit_score', '>', 0)
            ->where('user_id', $this->userId);

        $creditsList = $creditsListDb->order('updated_at DESC')
            ->page($page, $pageSize)
            ->select() ?: [];

        foreach ($creditsList as &$item) {
            $item['kindCh'] = TransItem::transCreditScoreOption(Arr::get($item, 'kind'));
            $item['timeCh'] = date('Y-m-d H:i', Arr::get($item, 'created_at'));
        }

        $this->response($creditsList);

    }





}
